package controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import dao.SanphamDAO;
import dao.ThamsochungDAO;

import pojo.Sanpham;
import util.BeanUtil;
import util.ConvertHelper;
import util.CountVisitor;
import util.SearchVisitor;

@ManagedBean(name = "trangKetQuaTimKiemCBBean")
@ViewScoped
public class TrangKetQuaTimKiemCBBean implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private List<Sanpham> lstSanPham = new ArrayList<Sanpham>();
	
	// Dùng cho máy Sơn
	//private String chuoitimkiem = ConvertHelper.ConvertCP1252ToUTF8(((HeaderBean) BeanUtil
	//		.findBean("headerBean")).getChuoitimkiem());
	private String chuoitimkiem = ((HeaderBean) BeanUtil
			.findBean("headerBean")).getChuoitimkiem();
			
	public TrangKetQuaTimKiemCBBean()
	{
		System.out.println("Vao trang tim kiem");
		System.out.println(chuoitimkiem);
		TimKiemTheoTenSanPham();
	}

	private void TimKiemTheoTenSanPham()
	{
		if(chuoitimkiem != null)
		{
			Map<String,String> params =  FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
			String thututrang = params.get("thututrang");
			
			int index = 1;
			if(thututrang != null)
				index = Integer.parseInt(thututrang);
			
			int nSPTrenTrang = LaySoSPTrenTrang();
				
			int FromIndex = nSPTrenTrang * (index - 1);
			
			SanphamDAO spdao = new SanphamDAO();
			SearchVisitor sv = new SearchVisitor();
			
			System.out.println(nSPTrenTrang);
			System.out.println(chuoitimkiem);
			
			spdao.accept(sv, chuoitimkiem, FromIndex, nSPTrenTrang);
			lstSanPham = sv.getResultSanPham();

		}
	}
	
	public int LaySoSPTrenTrang()
	{
		ThamsochungDAO thamsochung = new ThamsochungDAO();
        return Integer.parseInt(thamsochung.LayGiaTriCuaThamSo(ThamsochungDAO.TenThamSo.SO_SAN_PHAM_TREN_TRANG).toString());
	}
	
	public int XacDinhSoTrang()
	{
		CountVisitor cv = new CountVisitor();
		SanphamDAO spdao = new SanphamDAO();
		
		spdao.accept(cv, chuoitimkiem, null, null);
		
		int nSPTrenTrang = LaySoSPTrenTrang();
		int nSanPham = cv.getTotalSanPham();
		
        int nTrang =  nSanPham / nSPTrenTrang;
        nTrang = nSanPham % nSPTrenTrang == 0 ? nTrang: nTrang + 1;
		
		return nTrang;
	}
	
	public List<Sanpham> getLstSanPham() {
		return lstSanPham;
	}

	public void setLstSanPham(List<Sanpham> lstSanPham) {
		this.lstSanPham = lstSanPham;
	}

	public String getChuoitimkiem() {
		return chuoitimkiem;
	}

	public void setChuoitimkiem(String chuoitimkiem) {
		this.chuoitimkiem = chuoitimkiem;
	}

	
	
	
	
}
